<?php


namespace app\common\aliyun;

class Oss
{
	public $accessKeyId = "";
	public $accessSecret = "";
	public $bucket = "";
	public $endpoint = "";
	public $config = [];
	public function __construct($config = [])
	{
		if (!$config) {
			$config = \app\common\server\ConfigServer::get("file_storage", "aliyun");
		}
		$this->config = $config;
		$this->accessKeyId = $config["accessKeyId"];
		$this->accessSecret = $config["accessSecret"];
		$this->bucket = $config["bucket"];
		$this->endpoint = $config["endpoint"];
	}
	public function upload($filePath, $object)
	{
		$accessKeyId = $this->accessKeyId;
		$accessKeySecret = $this->accessSecret;
		$endpoint = $this->endpoint;
		$bucket = $this->bucket;
		try {
			$ossClient = new \OSS\OssClient($accessKeyId, $accessKeySecret, $endpoint);
			$result = $ossClient->uploadFile($bucket, $object, $filePath);
			return $result;
		} catch (\OSS\Core\OssException $e) {
			return $e->getMessage();
		}
	}
	public function getUrl($object, $timeout = 0)
	{
		$accessKeyId = $this->accessKeyId;
		$accessKeySecret = $this->accessSecret;
		$endpoint = $this->endpoint;
		$bucket = $this->bucket;
		try {
			$ossClient = new \OSS\OssClient($accessKeyId, $accessKeySecret, $endpoint);
			$options = [$ossClient::OSS_VERSION_ID => md5(time() . $object)];
			return $ossClient->signUrl($bucket, $object, $timeout, "GET", $options);
		} catch (\OSS\Core\OssException $e) {
			return false;
		}
	}
}